package com.ruoyi.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLOutput;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

@Slf4j
public class LocationUtil {
    private static final String API_KEY = "a8f88bccae485ac4d96e73f4fc3ff161"; // 在高德地图开发者平台申请的API Key
    private static final String WEATHER_API_URL = "https://restapi.amap.com/v3/weather/weatherInfo";
//    public static void main(String[] args) {
//        double longitude = 117.21775; // 经度
//        double latitude = 31.721585;  // 纬度
//        try {
//            JSONObject address = reverseGeoCode(longitude, latitude);
//            System.out.println("位置信息：" + address);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    //    public static void main(String[] args) {
//        String address = "浙江省杭州市钱塘区浙江理工大学25号楼"; // 要查询的地址
//        try {
//            double[] location = geocode(address);
//            if (location != null) {
//                double longitude = location[0]; // 经度
//                double latitude = location[1];  // 纬度
//
//                System.out.println("经度：" + longitude);
//                System.out.println("纬度：" + latitude);
//            } else {
//                System.out.println("未找到对应位置信息。");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//    public static void main(String[] args) {
//        double latitude = 30.35252; // 替换为实际纬度
//        double longitude = 120.35369; // 替换为实际经度
//
//        try {
//            JSONObject weatherData = getWeatherData(latitude, longitude);
//            System.out.println(weatherData);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    /**
     * 根据经纬度信息获取当地天气
     * @param latitude
     * @param longitude
     * @return
     * @throws IOException
     */
    public static JSONObject getWeatherData(double latitude, double longitude) throws IOException {
        JSONObject jsonObject = reverseGeoCode(longitude,latitude);
        log.info("json"+jsonObject);
        String adcode = jsonObject.getString("adcode");
        String apiUrl = WEATHER_API_URL + "?key=" + API_KEY + "&city=" + adcode +"&extensions=" + "base";
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(apiUrl);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String weatherData = EntityUtils.toString(entity);
        JSONObject weatherObj = weatherDataParser(weatherData);
        return weatherObj;
    }

    private static JSONObject weatherDataParser(String weatherData){
        // 将weatherData解析为JSONObject
        JSONObject jsonObject = JSONObject.parseObject(weatherData);
        // 获取lives字段对应的JSONArray
        JSONArray livesArray = jsonObject.getJSONArray("lives");
        // 获取第一个元素（如果有多个元素，则需要遍历）
        JSONObject liveData = livesArray.getJSONObject(0);
        // 提取weather和temperature_float字段的值
        String weather = liveData.getString("weather");
        String temperatureFloat = liveData.getString("temperature_float");
        JSONObject weatherObj = new JSONObject();
        weatherObj.put("weather",weather);
        weatherObj.put("temperature",temperatureFloat);
        return weatherObj;
    }


    /**
     * 根据经纬度获取位置信息
     * @param longitude
     * @param latitude
     * @return
     * @throws IOException
     */
    public static JSONObject reverseGeoCode(double longitude, double latitude) throws IOException {
        String urlStr = "https://restapi.amap.com/v3/geocode/regeo?output=json&location="
                + longitude + "," + latitude + "&key=" + API_KEY;

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        conn.disconnect();
        // 解析JSON数据，获取地理位置信息
        JSONObject address = parseJsonResponse(response.toString());
        return address;
    }
    private static JSONObject parseJsonResponse(String jsonResponse) {
        JSONObject jsonObject = JSON.parseObject(jsonResponse);
        log.info(jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").toJSONString());
        String city = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getString("city");
        String province = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getString("province");
        String district = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getString("district");
        String formattedAddress = jsonObject.getJSONObject("regeocode").getString("formatted_address");
        String adcode = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getString("adcode");
        System.out.println("城市：" + city);
        System.out.println("详细地址：" + formattedAddress);
        System.out.println("城市编码：" + adcode);
        System.out.println("省份：" + province);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("city",city);
        jsonObject1.put("formattedAddress",formattedAddress);
        jsonObject1.put("adcode",adcode);
        jsonObject1.put("province",province);
        jsonObject1.put("district",district);
        return jsonObject1;
    }

    /**
     * 根据输入地区信息获得经纬度
     * @param address
     * @return
     * @throws IOException
     */
    public static double[] geocode(String address) throws IOException {
            String encodedAddress = URLEncoder.encode(address, "UTF-8");
            String urlStr = "https://restapi.amap.com/v3/geocode/geo?address=" + encodedAddress + "&key=" + API_KEY;

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            reader.close();
            conn.disconnect();

            // 解析JSON数据，获取经纬度信息
            return parseLocaJsonResponse(response.toString());
    }

    private static double[] parseLocaJsonResponse(String jsonResponse) {
            try {
                // 在这里解析JSON数据，提取经纬度信息
                // 这里使用了一种简单的方式，你可以使用JSON库来解析更复杂的数据
                JSONObject jsonObject = JSON.parseObject(jsonResponse);
                JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                if (geocodes.size() > 0) {
                    JSONObject location = geocodes.getJSONObject(0);
                    String[] coordinates = location.getString("location").split(",");
                    double longitude = Double.parseDouble(coordinates[0]);
                    double latitude = Double.parseDouble(coordinates[1]);
                    return new double[]{longitude, latitude};
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
    }
}